'use strict';

exports.main = async (event, context) => {
	try {
		const db = uniCloud.database();
		const collection = db.collection('data');
		
		// 获取传入的设备数据
		const {
			temperature,
			humidity,
			uv,
			ph,
			soil,
			rain,
			light,
			led,
			fan,
			water,
			node_id
		} = event;
		
		// 构建要插入的数据对象
		const dataToInsert = {
			temperature: parseFloat(temperature) || 0,
			humidity: parseFloat(humidity) || 0,
			uv: parseFloat(uv) || 0,
			ph: parseFloat(ph) || 0,
			soil: parseFloat(soil) || 0,
			rain: parseFloat(rain) || 0,
			light: parseFloat(light) || 0,
			led: Boolean(led),
			fan: Boolean(fan),
			water: Boolean(water),
			node_id: parseInt(node_id) || 0, // 添加设备节点ID
			timestamp: Date.now(), // 添加时间戳
			createTime: new Date() // 添加创建时间
		};
		
		// 插入数据到云数据库
		const result = await collection.add(dataToInsert);
		
		return {
			code: 0,
			message: '数据添加成功',
			data: {
				id: result.id,
				insertedData: dataToInsert
			}
		};
		
	} catch (error) {
		console.error('添加数据失败:', error);
		return {
			code: -1,
			message: '数据添加失败',
			error: error.message
		};
	}
};